<?php

namespace seecms\lib;

use magein\utils\Tree;

class TreeSelect
{
    protected $data;

    protected $title_filed = 'title';

    protected $parent_id = 'parent_id';

    public function __construct($data, $title_filed = null, $parent_id = null)
    {
        $tree = new Tree($data);
        $tree->setParentId($parent_id ?: $this->parent_id);
        $this->data = $tree->floor();
        if ($title_filed) {
            $this->title_filed = $title_filed;
        }
    }

    public function options($top = null, $separator = null)
    {
        $options = $top ?: [0 => '顶级分类'];
        $separator = $separator ?: '|--';
        $title = $this->title_filed ?: 'title';
        if ($this->data) {
            foreach ($this->data as $item) {
                $sp = '';
                $level = $item['__level__'];
                if ($level > 1) {
                    $sp = str_repeat($separator, ($level - 1));
                }
                $options[$item['id']] = $sp . ($item[$title] ?? '');
            }
        }
        return $options;
    }
}